package com.geralt.im.commands.impl;

import java.util.ArrayList;
import java.util.HashSet;

import com.geralt.im.command.Command;
import com.geralt.im.commandenum.Code;
import com.geralt.im.dao.impl.CustomerDaoImlp;
import com.geralt.im.model.Customer;
import com.geralt.im.model.Message;
import com.geralt.im.protocol.Response;
import com.geralt.im.server.IMServer;

public class LoginCommand extends Command{
	
	@Override
	public Response excute() {
		Customer customer = (Customer) parameter.get("LOGIN");		
		// validate(customer.getId())
		String id = customer.getId();
		String password = customer.getPassword();
		CustomerDaoImlp dao = new CustomerDaoImlp();
		boolean validate = true;
		if(IMServer.map.containsKey(id)){
			validate=false;
			return getBadRequest("you want to login is exists");
		}
		if(dao.query(id)==null){
			validate=false;
			return getBadRequest("the user is not exist,please register");
		}
		if(dao.query(id,password)==null){
			validate=false;
			return getBadRequest("the password is not correct.");
		}
		receivers.clear();
		if(validate){
			IMServer.map.put(id, getSession());
			ArrayList<String> list = getReceivers();
			list.addAll(IMServer.map.keySet());
			Response response = new Response();
			response.setStatusCode(Code.OK);
			response.setType("LIST");
			response.getParameter().put("MAP", new HashSet<>(IMServer.map.keySet()));
			System.out.println(id);
			return response;
		}
		return getBadRequest("Unknown Error");
		
	}
}
